package com.jeedroid.weibo;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class LoginActivity extends Activity
{
private WebView webview;
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);
		webview=(WebView)findViewById(R.id.webviewId);
		Intent intent=getIntent();
		String url=intent.getStringExtra("req_yes_reqtoken_url");
		WebSettings webSettings=webview.getSettings();
		webSettings.setJavaScriptEnabled(true);
		webSettings.setSupportZoom(true);
		webview.requestFocus();
		webview.loadUrl(url);
		
		//绑定java对象到JavaScript中，这样就能在JavaScript中调用java对象，实现通信。
				//这种方法第一个参数就是java对象，第二个参数表示java对象的别名，在JavaScript中使用
				webview.addJavascriptInterface(new JavaScriptInterface(), "Methods");
				WebViewClient client = new WebViewClient()
				{
					/**
					 * 回调方法，当页面加载完毕后执行
					 */
					@Override
					public void onPageFinished(WebView view, String url)
					{
						//执行获取授权码的JavaScript
						view.loadUrl("javascript:window.Methods.getHTML('<head>'+document.getElementsByTagName('body')[0].innerHTML+'</head>');");
						super.onPageFinished(view, url);
					}
				};
				webview.setWebViewClient(client);
			}
	
	class JavaScriptInterface
	{
		
		public void getHTML(String html)
		{
			String verifier = getVerifier(html);
		}

		public String getVerifier(String html)
		{
			String ret = "";
			String regEx = "授权码：[0-9]{6}";
			Pattern p = Pattern.compile(regEx);
			Matcher m = p.matcher(html);
			boolean result = m.find();
			if (result)
			{
				ret = m.group(0).substring(4);
			}
			return ret;
		}
	}
}